package com.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.example.captcha.model.CaptchaProperties;
import com.example.captcha.model.SessionProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private static final Integer CAPTCHA_TIME_OUT=30*60;
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping(value = "/getCaptcha",produces = "image/png")
    public void getCaptcha(HttpServletResponse response, HttpSession session)  {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight(),
                captchaProperties.getCodecount(), captchaProperties.getThickness());
        String code = captcha.getCode();
        response.setHeader("Content-Type","image/jpeg");
        //打印验证码日志
        System.out.println(code);
        try {
            captcha.write(response.getOutputStream());
            response.getOutputStream().close();
            /**
             * 空指针判断
             *
             */
            SessionProperties sessionName=new SessionProperties();
            if (captchaProperties.getSession()!=null){
                sessionName.setCode(captchaProperties.getSession().getCode());
                sessionName.setTime(captchaProperties.getSession().getTime());
            }
            session.setAttribute(sessionName.getCode(),code);
            session.setAttribute(sessionName.getTime(),System.currentTimeMillis());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/check")
    public Boolean check(String captcha,HttpSession session){
        //参数校验
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        //空校验,和超时校验
        SessionProperties sessionName=new SessionProperties();
        if (captchaProperties.getSession()!=null){
            sessionName.setCode(captchaProperties.getSession().getCode());
            sessionName.setTime(captchaProperties.getSession().getTime());
        }
        String code=(String) session.getAttribute(sessionName.getCode());
        if(code==null||(Long)session.getAttribute(sessionName.getTime())==null||
                (System.currentTimeMillis()-(Long)session.getAttribute(captchaProperties.getSession().getTime())<CAPTCHA_TIME_OUT)){
            return false;
        }
        if(code.equalsIgnoreCase(captcha)){
            return true;
        }
        return false;
    }
}
